from werkzeug.security import generate_password_hash, check_password_hash
import sqlite3
import os
from flask_login import UserMixin

class UserDB:
    def __init__(self):
        self.db_path = 'database/users.db'
        self._init_db()

    def _init_db(self):
        # 确保数据库目录存在
        os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
        
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        
        # 创建用户表
        c.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                is_admin INTEGER DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # 创建操作日志表
        c.execute('''
            CREATE TABLE IF NOT EXISTS operation_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                operation_type TEXT NOT NULL,
                file_name TEXT,
                status TEXT,
                error_message TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (id)
            )
        ''')
        
        # 检查是否需要添加error_message列
        c.execute("PRAGMA table_info(operation_logs)")
        columns = [column[1] for column in c.fetchall()]
        if 'error_message' not in columns:
            c.execute('ALTER TABLE operation_logs ADD COLUMN error_message TEXT')
        
        conn.commit()
        conn.close()

    def create_user(self, username, password, is_admin=0):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        try:
            c.execute(
                'INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, ?)',
                (username, generate_password_hash(password), is_admin)
            )
            conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False
        finally:
            conn.close()

    def verify_user(self, username, password):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute('SELECT id, password_hash, is_admin FROM users WHERE username = ?', (username,))
        user = c.fetchone()
        conn.close()
        
        if user and check_password_hash(user[1], password):
            return {'id': user[0], 'username': username, 'is_admin': user[2]}
        return None

    def log_operation(self, user_id, operation_type, file_name, status, error_message=None):
        conn = sqlite3.connect(self.db_path)
        c = conn.cursor()
        c.execute(
            'INSERT INTO operation_logs (user_id, operation_type, file_name, status, error_message) VALUES (?, ?, ?, ?, ?)',
            (user_id, operation_type, file_name, status, error_message)
        )
        conn.commit()
        conn.close()

    def _get_db_connection(self):
        """获取数据库连接"""
        return sqlite3.connect(self.db_path)

class User(UserMixin):
    def __init__(self, user_data):
        self.id = user_data['id']
        self.username = user_data['username']
        self.is_admin = user_data['is_admin']
        self._is_active = True

    @property
    def is_active(self):
        return self._is_active
